<script setup>
import GoEasy from 'goeasy'
import { reactive, ref, onUnmounted } from 'vue'
const goEasy = ref(null)
// 初始化GoEasy
function initGoEasy() {
  goEasy.value = GoEasy.getInstance({
    host: 'hangzhou.goeasy.io', //新加坡host：singapore.goeasy.io
    appkey: 'BC-781204ebb2a44b62a402e494b02d127d', //替换为您的应用appkey
    modules: ['pubsub']
  })

  //建立连接
  goEasy.value.connect({
    onSuccess: function () {
      //连接成功
      console.log('连接成功:GoEasy connect successfully.') //连接成功
    },
    onFailed: function (error) {
      //连接失败
      console.log(
        '连接失败:Failed to connect GoEasy, code:' + error.code + ',error:' + error.content
      )
    },
    onprogress: function (attempt) {
      //连接中
      console.log('连接中:Connecting GoEasy, attempt:' + attempt)
    }
  })
  //订阅消息
  goEasy.value.pubsub.subscribe({
    channel: 'test_channel', //替换为您自己的channel
    onMessage: function (message) {
      //收到消息
      console.log('收到消息Channel:' + message.channel + ' content:' + message.content)
    },
    onSuccess: function () {
      console.log('Channel订阅成功。')
    },
    onFailed: function (error) {
      console.log('Channel订阅失败, 错误编码：' + error.code + ' 错误信息：' + error.content)
    }
  })
}
initGoEasy()
function sendMsg() {
  goEasy.value.pubsub.publish({
    channel: 'my_channel', //替换为您自己的channel
    message: 'Hello GoEasy!', //替换为您想要发送的消息内容
    qos: 1, // 为1启用补发，0无需补发，默认为0。SDK需升级至2.6.2以上
    onSuccess: function () {
      console.log('消息发布成功。')
    },
    onFailed: function (error) {
      console.log('消息发送失败，错误编码：' + error.code + ' 错误信息：' + error.content)
    }
  })
}
onUnmounted(() => {
  // 断开连接
  goEasy.value.disconnect()
})
</script>

<template>
  <div>
    <el-button @click="sendMsg">发送消息</el-button>
  </div>
</template>

<style lang="scss" scoped></style>
